package com.css.fxfzxczh.modules.report.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.css.fxfzxczh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzxczh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzxczh.base.dict.repository.entity.DictItemEntity;
import com.css.fxfzxczh.base.dict.service.DictService;
import com.css.fxfzxczh.constants.XczhConstants;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.aftershockSequence.entity.AftershockSequence;
import com.css.fxfzxczh.modules.aftershockSequence.repository.AftershockSequenceRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.repository.LifelineRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.repository.SamPoiDataRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.entity.HouDamSta;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.entity.AdministrationAreaHousesDirectEconomicLosses;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.entity.HouseFailureRatioEntity;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.entity.HouseLossRatioEntity;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.repository.HouseEconomicLossAssessRepository;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseFinishLossAssess.entity.MhFinishHouseArea;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseFinishLossAssess.repository.HouseFinishLossAssessRepository;
import com.css.fxfzxczh.modules.evaluationSummary.entity.EconomicLossesSummary;
import com.css.fxfzxczh.modules.evaluationSummary.entity.LifelineSystemLoss;
import com.css.fxfzxczh.modules.evaluationSummary.entity.PersonnelInjuryAssessment;
import com.css.fxfzxczh.modules.evaluationSummary.entity.ResettlementPopulationEvaluation;
import com.css.fxfzxczh.modules.evaluationSummary.repository.EnterpriseDirectEconomyRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.entity.SurTaskManage;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.repository.SurTaskManageRepository;
import com.css.fxfzxczh.modules.instrumentIntensity.entity.InstrumentIntensity;
import com.css.fxfzxczh.modules.instrumentIntensity.repository.InstrumentIntensityRepository;
import com.css.fxfzxczh.modules.lossAssessment.houseCategoryArea.entity.HouseCategoryArea;
import com.css.fxfzxczh.modules.lossAssessment.houseCategoryArea.repository.HouseCategoryAreaRepository;
import com.css.fxfzxczh.modules.lossAssessment.houseCategoryArea.vo.HouseCategoryAreaVo;
import com.css.fxfzxczh.modules.lossAssessment.resetPrice.entity.ResetPrice;
import com.css.fxfzxczh.modules.lossAssessment.resetPrice.repository.ResetPriceRepository;
import com.css.fxfzxczh.modules.map.entity.DrawSeismicInfluence;
import com.css.fxfzxczh.modules.map.service.ShpDataService;
import com.css.fxfzxczh.modules.report.CustomXWPFDocument;
import com.css.fxfzxczh.modules.report.entity.Report;
import com.css.fxfzxczh.modules.report.entity.ReportTemplate;
import com.css.fxfzxczh.modules.report.repository.ReportRepository;
import com.css.fxfzxczh.modules.report.repository.ReportTemplateRepository;
import com.css.fxfzxczh.modules.report.service.ReportService;
import com.css.fxfzxczh.modules.report.vo.CreateReportVo;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.repository.EarEveManageRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.repository.PersonnelManagementRepository;
import com.css.fxfzxczh.util.*;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.hibernate.type.BigDecimalType;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Value("${image.localDir}")
    private String localDir;
    @Autowired
    private EarEveManageRepository earEveManageRepository;
    @Autowired
    private AttachmentInfoService attachmentInfoService;
    @Autowired
    private ReportTemplateRepository reportTemplateRepository;
    @Autowired
    private ReportRepository reportRepository;
    @Autowired
    private SUserService sUserService;
    @Autowired
    private EarEveManageService earEveManageService;
    @Resource
    HouseCategoryAreaRepository houseCategoryAreaRepository;
    @Autowired
    EnterpriseDirectEconomyRepository enterpriseDirectEconomyRepository;
    @Autowired
    private PersonnelManagementRepository personnelManagementRepository;
    @Autowired
    SamPoiDataRepository samPoiDataRepository;
    @Autowired
    LifelineRepository lifelineRepository;
    @Autowired
    private ShpDataService shpDataService;
    @Autowired
    SurTaskManageRepository surTaskManageRepository;
    @Autowired
    HouseEconomicLossAssessRepository houseEconomicLossAssessRepository;
    @Autowired
    DictService dictService;
    @Autowired
    ResetPriceRepository resetPriceRepository;
    @Autowired
    InstrumentIntensityRepository instrumentIntensityRepository;
    @Autowired
    private AftershockSequenceRepository aftershockSequenceRepository;
    @Autowired
    private RestTemplate restTemplate;
    @Override
    public String getNumber(String id) {
        EarEveManage earEveManage = earEveManageRepository.findById(id);
        return earEveManage.getEventCode() + "ZPBG01";

    }

    @Override
    public List<Report> getReports(String xsemId) {
        return reportRepository.getReports(xsemId);
    }

    @Override
    public void updateReport(Report report) {
        report.setUpdateUser(PlatformSessionUtils.getUserId());
        report.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        reportRepository.updateReport(report);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createReport(HttpServletResponse response, CreateReportVo vo) throws Exception {
        //InputStream input = ClassLoader.getSystemResourceAsStream("template/现场灾害-报告模板.docx");

        ReportTemplate reportTemplate = reportTemplateRepository.getById(vo.getRtId());
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(reportTemplate.getFileId());
        InputStream input = new FileInputStream(attach.getFileDirId() + attach.getAttachPath());
        CustomXWPFDocument xwpfDocument = new CustomXWPFDocument(input);
        Map reportData = getReportData1();
        writeData(xwpfDocument, reportData);
        String fileName = vo.getName()+".docx";
        String realFileName = getRealFileName(fileName);
        String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
        String savePath = localDir + dateDir;
        File file = new File(savePath, realFileName);
        if (!new File(savePath).exists()) new File(savePath).mkdirs();
        OutputStream os = new FileOutputStream(file);
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        xwpfDocument.write(os);
        input.close();
        os.flush();
        os.close();
        //保存到数据库
        String uuid = UUIDGenerator.getUUID();
        AttachmentInfoEntity attachmentInfoEntity = buildAttachment(uuid, fileName, dateDir, realFileName);
        attachmentInfoService.save(Arrays.asList(attachmentInfoEntity));
        this.saveRport(uuid, vo);
        transReportMsgToCpxx(savePath+File.separator+realFileName,vo.getName(), (String) reportData.get("name"));
    }

    private void transReportMsgToCpxx(String picPath, String fileName, String keyword) throws Exception {
        String userId = PlatformSessionContext.getUserID();
        String userJson = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        //获取创建人单位
        String orgName = sUser.getOrgName();
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("cpxxRestUrl") + "/infAchievement/dockingOtherSystem";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization", IdUtil.simpleUUID());
        File newfile = new File(picPath);
        Map<String, String> valueMap = new HashMap<>();
        valueMap.put("dataOrigin", "6");
        valueMap.put("sign", "1");
        valueMap.put("publishingUnit", orgName);
        valueMap.put("createUser", userId);
        valueMap.put("achievementName", fileName);
        valueMap.put("keyword", keyword);
        Map<String, MultipartFile> fileParams = new HashMap<>();
        //本地文件转为MultipartFile
        MultipartFile file = RemoteTransfer.pathToMultipartFile(newfile);
        fileParams.put("file", file);
        String res = RemoteTransfer.uploadFile(url, fileParams, valueMap, null);
    }

    private void saveRport(String uuid, CreateReportVo vo) {
        reportRepository.deleteByXsemId(vo.getXsemId());
        Report report = new Report();
        BeanUtils.copyProperties(vo, report);
        report.setFileId(uuid);
        report.setId(UUIDGenerator.getUUID());
        report.setCreateUserId(PlatformSessionUtils.getUserId());
        report.setDelFlag(YNEnum.N.toString());
        String sUser1 = sUserService.getSUser(PlatformSessionUtils.getUserId());
        SUser sUser = CreateGson.createGson().fromJson(sUser1, SUser.class);
        report.setUnit(sUser.getOrgName());
        reportRepository.save(report);
    }


    private void writeData(CustomXWPFDocument xwpfDocument, Map reportData) {
        //替换段落字段和图片
        replaceInPara(xwpfDocument, reportData);
        //表格
        createTable(xwpfDocument, reportData);
    }

    private void createTable(CustomXWPFDocument xwpfDocument, Map reportData) {
        List<XWPFTable> tables = xwpfDocument.getTables();
        for (int i = 0; i < tables.size(); i++) {
            if (i == 0) {
                replaceTable(tables.get(i), reportData);
            }else if(i==1){
                Map<String, List<List<String>>> map = (Map<String, List<List<String>>>) reportData.get("tableData1");
                if (!PlatformObjectUtils.isEmpty(map)) {
                    // 记录初始下标
                    int headerRowCount = 2; // 假设表头有两行
                    int startIndex = headerRowCount;
                    int tempIndex = startIndex;
                    XWPFTable table = tables.get(i);
                    Iterator<Map.Entry<String, List<List<String>>>> iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<List<String>>> next = iterator.next();
                        List<List<String>> value = next.getValue();
                        int size = value.size();
                        for (int a = 0; a < size; a++) {
                            table.createRow();
                        }
                        tempIndex = startIndex;
                        List<XWPFTableRow> rows = table.getRows();
                        for (int b = 0; b < size; b++) { // 修改为从0开始
                            XWPFTableRow newRow = table.getRow(startIndex);

                            // 确保行中有足够的单元格
                            int cellCount = newRow.getTableCells().size();
                            int requiredCellCount = value.get(b).size();
                            for (int c = cellCount; c < requiredCellCount; c++) {
                                newRow.createCell();
                            }

                            List<XWPFTableCell> cells = newRow.getTableCells();
                            for (int j = 0; j < cells.size(); j++) {
                                XWPFTableCell cell = cells.get(j);
                                List<String> strList = value.get(b);
                                if (j < strList.size()) {
                                    // cell.setText(strList.get(j));
                                    center(cell, strList.get(j), 14, "黑体");
                                }
                            }
                            startIndex++;
                        }
                        // 合并单元格
                        for (int rowIndex = tempIndex; rowIndex < startIndex; rowIndex++) {
                            for (int j = 0; j < 1; j++) {
                                XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(j);
                                if (mergeCell1 != null) {
                                    if (rowIndex == tempIndex) {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                                    } else {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                                    }
                                    center(mergeCell1);
                                }
                            }
                        }
                    }
                }



            }else if(i==2){
                List<List<String>> list = (List<List<String>>) reportData.get("tableData2");
                if(list.size()>0){
                    insertTable(tables.get(i), list,14,"黑体");
                }

            }else if(i==3){
                Map<String, List<List<String>>> map= (Map<String, List<List<String>>>) reportData.get("tableData3");
                if(!PlatformObjectUtils.isEmpty(map)){
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    XWPFTable table = tables.get(i);
                    Iterator<Map.Entry<String, List<List<String>>>> iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<List<String>>> next = iterator.next();
                        List<List<String>> value = next.getValue();
                        int size = value.size();
                        for (int a = 0; a < size; a++) {
                            table.createRow();
                        }
                        tempIndex = startIndex;
                        List<XWPFTableRow> rows = table.getRows();
                        for (int b = 1; b <= size; b++) {
                            XWPFTableRow newRow = table.getRow(startIndex);


                            //copyStyle(newRow, header);
                            List<XWPFTableCell> cells = newRow.getTableCells();
                            for (int j = 0; j < cells.size(); j++) {
                                XWPFTableCell cell = cells.get(j);
                                List<String> strList = value.get(b - 1);
                                if(j<strList.size()){
                                    //cell.setText(strList.get(j));
                                    center(cell,strList.get(j),14,"黑体");
                                }
                            }
                            startIndex++;
                        }
                        //合并单元格
                        for (int rowIndex = tempIndex; rowIndex < rows.size(); rowIndex++) {
                            for (int j = 0; j < 1; j++) {
                                XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(j);
                                if (mergeCell1 != null) {
                                    if (rowIndex == tempIndex) {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                                    } else {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                                    }
                                    center(mergeCell1);
                                }
                            }

                        }
                    }
                }

            }else if(i==4){
                Map<String, List<List<String>>> map= (Map<String, List<List<String>>>) reportData.get("tableData4");
                if(!PlatformObjectUtils.isEmpty(map)){
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    XWPFTable table = tables.get(i);
                    Iterator<Map.Entry<String, List<List<String>>>> iterator = map.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<List<String>>> next = iterator.next();
                        List<List<String>> value = next.getValue();
                        int size = value.size();
                        for (int a = 0; a < size; a++) {
                            table.createRow();
                        }
                        tempIndex = startIndex;
                        List<XWPFTableRow> rows = table.getRows();
                        for (int b = 1; b <= size; b++) {
                            XWPFTableRow newRow = table.getRow(startIndex);


                            //copyStyle(newRow, header);
                            List<XWPFTableCell> cells = newRow.getTableCells();
                            for (int j = 0; j < cells.size(); j++) {
                                XWPFTableCell cell = cells.get(j);
                                List<String> strList = value.get(b - 1);
                                if(j<strList.size()){
                                    //cell.setText(strList.get(j));
                                    center(cell,strList.get(j),11,"黑体");
                                }
                            }
                            startIndex++;
                        }
                        //合并单元格
                        for (int rowIndex = tempIndex; rowIndex < rows.size(); rowIndex++) {
                            for (int j = 0; j < 1; j++) {
                                XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(j);
                                if (mergeCell1 != null) {
                                    if (rowIndex == tempIndex) {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                                    } else {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                                    }
                                    center(mergeCell1);
                                }
                            }

                        }
                    }
                }

            }else if (i == 5) {
                replaceTable(tables.get(i), reportData);
            }else if(i==6){
                List<List<String>> list = (List<List<String>>) reportData.get("tableData6");
                if(list.size()>0){
                    insertTable(tables.get(i), list,16,"仿宋_GB2312");
                }

            }else if(i==9){
                List<List<String>> list = (List<List<String>>) reportData.get("tableData9");
                if(list.size()>0){
                    insertTable1(tables.get(i), list,11,"等线");
                }
            }else if(i==10){
                List<List<String>> list = (List<List<String>>) reportData.get("tableData10");
                if(list.size()>0){
                    insertTable2(tables.get(i), list,11,"等线");
                }
            }


        }

    }

    private void replaceTable(XWPFTable table, Map reportData){
        if (table.getRows().size() > 1) {
            //判断表格内容是否可以替换
            String cellText = table.getText();
            if (StrUtil.isNotBlank(cellText) && cellText.contains("{")){
                List<XWPFTableRow> rows = table.getRows();
                //遍历表格,并替换模板
                eachTable(rows, reportData);
            }
        }
    }


    private void center(XWPFTableCell cell,String value,Integer size,String typeface) {
        List<XWPFParagraph> paragraphs = cell.getParagraphs();
        for (XWPFParagraph xwpfParagraph : paragraphs) {
            xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun run = xwpfParagraph.createRun();
            run.setText(value);
            run.setFontSize(size);
            run.setFontFamily(typeface);

        }
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
    }

    private void center(XWPFTableCell cell) {
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        CTTc cttc = cell.getCTTc();
        CTTcPr ctPr = cttc.addNewTcPr();
        ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
    }

    private void insertTable(XWPFTable table, List<List<String>> list,Integer size,String typeface) {
        //创建行,根据需要插入的数据添加新行，不处理表头
        for (int i = 1; i <= list.size(); i++) {
            XWPFTableRow row = table.createRow();
            row.setHeight(20 * 10);
        }
        for (int i = 0; i < list.size(); i++) {
            List<String> strings = list.get(i);
            XWPFTableRow row = table.getRow(i + 1);
            //设置表格内容不会跨页换行
            row.setCantSplitRow(true);
            for (int j = 0; j < strings.size(); j++) {
                XWPFTableCell cell = row.getCell(j);
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                for (XWPFParagraph xwpfParagraph : paragraphs) {
                    xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
                    XWPFRun run = xwpfParagraph.createRun();
                    run.setText(list.get(i).get(j));
                    run.setFontSize(size);
                    run.setFontFamily(typeface);

                }
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                CTTc cttc = cell.getCTTc();
                CTTcPr ctPr = cttc.addNewTcPr();
                ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
                cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
            }
        }
    }

    private void insertTable1(XWPFTable table, List<List<String>> list, Integer size, String typeface) {
        table.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 内部水平边框
        table.setInsideVBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 内部垂直边框
        table.setTopBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 顶部边框
        table.setBottomBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 底部边框
        table.setLeftBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 左侧边框
        table.setRightBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 右侧边框

        int startMergeIndex = 2;
        String evaluationSubName = list.get(0).get(0);
        for (int i = 2; i <= list.size() + 1; i++) {
            XWPFTableRow row = table.createRow();
            row.setCantSplitRow(true);
            int twipsPerInch = 1440;
            row.setHeight(twipsPerInch * 1 / 10);

            for (int j = 0; j < list.get(i - 2).size(); j++) {
                XWPFTableCell cell = row.getCell(j);
                insertValue(row, cell, size, typeface, list.get(i - 2).get(j));
                CTTc cttc = row.getCell(j).getCTTc();
                CTTcPr ctPr = cttc.addNewTcPr();
                ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
                cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
            }

            if (i <= list.size() && list.get(i - 1).get(0).equals(evaluationSubName)) {
                // 当前行的第一列值与前一行相同，继续合并
                continue;
            } else {
                // 当前行的第一列值与前一行不同，进行合并
                mergeCell(table, startMergeIndex, i , 0);
                startMergeIndex++;
            }

            // 更新下一组合并的起始行和当前合并值
            startMergeIndex = i;
            startMergeIndex++;
            if (i <= list.size()) {
                evaluationSubName = list.get(i - 1).get(0);
            }

        }
//        table.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 内部水平边框
//        table.setInsideVBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 内部垂直边框
//        table.setTopBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 顶部边框
//        table.setBottomBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 底部边框
//        table.setLeftBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 左侧边框
//        table.setRightBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 右侧边框
//        int startMergeIndex1 = 2; // 第一列合并的起始索引
//        int startMergeIndex2 = 2; // 第二列合并的起始索引
//        int startMergeIndex3 = 2; // 第三列合并的起始索引
//        int startMergeIndex4 = 2; // 第四列合并的起始索引
//
//        for (int i = 2; i <= list.size() + 1; i++) {
//            XWPFTableRow row = table.createRow();
//            row.setCantSplitRow(true);
//            int twipsPerInch = 1440;
//            row.setHeight(twipsPerInch * 1 / 10);
//
//            for (int j = 0; j < list.get(i - 2).size(); j++) {
//                XWPFTableCell cell = row.getCell(j);
//                insertValue(row, cell, size, typeface, list.get(i - 2).get(j));
//                CTTc cttc = row.getCell(j).getCTTc();
//                CTTcPr ctPr = cttc.addNewTcPr();
//                ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
//                cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
//            }
//
//            // 判断并合并第一列
//            if (i <= list.size() && list.get(i - 1).get(0).equals(list.get(i - 2).get(0))) {
//                continue;
//            }else{
//                mergeCell(table, startMergeIndex1, i, 0);
//                startMergeIndex1 = i;
//                startMergeIndex1++;
//            }
//
//            // 判断并合并第二列
//            if (i <= list.size() && !list.get(i - 1).get(1).equals(list.get(i - 2).get(1))) {
//                continue;
//            }else{
//                mergeCell(table, startMergeIndex2, i, 1);
//                startMergeIndex2 = i;
//                startMergeIndex2++;
//            }
//        }

    }


    /**
     * 合并单元格
     *
     * @param table         表格对象
     * @param beginRowIndex 开始行索引
     * @param endRowIndex   结束行索引
     * @param colIndex      合并列索引
     */
    public static void mergeCell(XWPFTable table, int beginRowIndex, int endRowIndex, int colIndex) {
        if (beginRowIndex == endRowIndex || beginRowIndex > endRowIndex) {
            return;
        }
        //合并行单元格的第一个单元格
        CTVMerge startMerge = CTVMerge.Factory.newInstance();
        startMerge.setVal(STMerge.RESTART);
        //合并行单元格的第一个单元格之后的单元格
        CTVMerge endMerge = CTVMerge.Factory.newInstance();
        endMerge.setVal(STMerge.CONTINUE);
        table.getRow(beginRowIndex).getCell(colIndex).getCTTc().getTcPr().setVMerge(startMerge);
        for (int i = beginRowIndex + 1; i <= endRowIndex; i++) {
            table.getRow(i).getCell(colIndex).getCTTc().getTcPr().setVMerge(endMerge);
        }
    }


    private void insertTable2(XWPFTable table, List<List<String>> list, Integer size, String typeface) {
        table.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 内部水平边框
        table.setInsideVBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 内部垂直边框
        table.setTopBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 顶部边框
        table.setBottomBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 底部边框
        table.setLeftBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 左侧边框
        table.setRightBorder(XWPFTable.XWPFBorderType.SINGLE, 1, 1, "000000"); // 右侧边框
        for (int i = 2; i <= list.size() + 1; i++) {
            XWPFTableRow row = table.createRow();
            row.setCantSplitRow(true);
            int twipsPerInch = 1440;
            row.setHeight(twipsPerInch * 1 / 10);
            for (int j = 0; j < list.get(i-2).size(); j++) {

                XWPFTableCell cell = row.getCell(j);
                insertValue(row,cell,size,typeface,list.get(i-2).get(j));
                CTTc cttc = row.getCell(j).getCTTc();
                CTTcPr ctPr = cttc.addNewTcPr();
                ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
                cttc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
            }
        }

        //插入小计行
        XWPFTableRow calculateTotaRow = table.createRow();
        //计算小计值
        List<String> calculateTotalList = calculateTotal(list);
        for (int a = 0; a < calculateTotalList.size(); a++) {
            XWPFTableCell cell = calculateTotaRow.getCell(a);
            insertValue(calculateTotaRow,cell,size,typeface,calculateTotalList.get(a));
        }



        //插入分项合计行
        XWPFTableRow subtotalRow = table.createRow();
        XWPFTableCell cell = subtotalRow.getCell(0);
        insertValue(subtotalRow,cell,size,typeface,"分项合计");


        // 合并单元格
        mergeCells(subtotalRow, 1, 8);
        // 计算合并单元格的和
        BigDecimal houseTotal = BigDecimal.ZERO;
        for (int col = 1; col <= 8; col++) {
            houseTotal = houseTotal.add(new BigDecimal(calculateTotalList.get(col)));
        }
        // 在合并单元格中插入合计值
        XWPFTableCell houseCell = subtotalRow.getCell(1);
        insertValue(subtotalRow,houseCell,size,typeface,String.valueOf(houseTotal));


        // 合并单元格
        mergeCells(subtotalRow, 9, 18);
        // 计算合并单元格的和
        BigDecimal lifeLineTotal = BigDecimal.ZERO;
        for (int col = 9; col <= 18; col++) {
            lifeLineTotal = lifeLineTotal.add(new BigDecimal(calculateTotalList.get(col)));
        }
        // 在合并单元格中插入合计值
        XWPFTableCell lifeLineCell = subtotalRow.getCell(9);
        insertValue(subtotalRow,lifeLineCell,size,typeface,String.valueOf(lifeLineTotal));


        XWPFTableCell enterpriseCell = subtotalRow.getCell(19);
        BigDecimal  enterpriseTotal = new BigDecimal(calculateTotalList.get(19));
        insertValue(subtotalRow,enterpriseCell,size,typeface,String.valueOf(enterpriseTotal));


        XWPFTableCell waterConCell = subtotalRow.getCell(20);
        BigDecimal waterConTotal = new BigDecimal(calculateTotalList.get(20));
        insertValue(subtotalRow,waterConCell,size,typeface,String.valueOf(waterConTotal));


        XWPFTableCell culturalRelCell = subtotalRow.getCell(21);
        BigDecimal culturalRelTotal = new BigDecimal(calculateTotalList.get(21));
        insertValue(subtotalRow,culturalRelCell,size,typeface,String.valueOf(culturalRelTotal));


        XWPFTableCell otherCell = subtotalRow.getCell(22);
        BigDecimal otherTotal = new BigDecimal(calculateTotalList.get(22));
        insertValue(subtotalRow,otherCell,size,typeface,String.valueOf(otherTotal));

        // 合并单元格
        mergeCells(subtotalRow, 23, 24);
        // 计算合并单元格的和
        BigDecimal indoorOutTotal = BigDecimal.ZERO;
        for (int col = 23; col <= 24; col++) {
            indoorOutTotal = indoorOutTotal.add(new BigDecimal(calculateTotalList.get(col)));
        }
        // 在合并单元格中插入合计值
        XWPFTableCell indoorOutCell = subtotalRow.getCell(1);
        insertValue(subtotalRow,indoorOutCell,size,typeface,String.valueOf(indoorOutTotal));


        XWPFTableCell totalCell = subtotalRow.getCell(25);
        BigDecimal total = new BigDecimal(calculateTotalList.get(25));
        insertValue(subtotalRow,totalCell,size,typeface,String.valueOf(total));



        //插入百分比行
        XWPFTableRow percentageRow = table.createRow();
        XWPFTableCell percentageCell = percentageRow.getCell(0);
        insertValue(percentageRow,percentageCell,size,typeface,"百分比");


        // 合并单元格，房屋百分比
        mergeCells(percentageRow, 1, 8);
        XWPFTableCell housePerCell = percentageRow.getCell(1);
        insertValue(percentageRow,housePerCell,size,typeface,(houseTotal.divide(total, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)))+"%");


        // 合并单元格，生命线百分比
        mergeCells(percentageRow, 9, 18);
        XWPFTableCell lifeLinePerCell = percentageRow.getCell(9);
        insertValue(percentageRow,lifeLinePerCell,size,typeface,(lifeLineTotal.divide(total, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)))+"%");


        //企业百分比
        XWPFTableCell enterprisePerCell = percentageRow.getCell(19);
        insertValue(percentageRow,enterprisePerCell,size,typeface,(enterpriseTotal.divide(total, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)))+"%");


        //水利百分比
        XWPFTableCell waterConPerCell = percentageRow.getCell(20);
        insertValue(percentageRow,waterConPerCell,size,typeface,(waterConTotal.divide(total, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)))+"%");


        //文物古建百分比
        XWPFTableCell culturalRelPerCell = percentageRow.getCell(21);
        insertValue(percentageRow,culturalRelPerCell,size,typeface,(culturalRelTotal.divide(total, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)))+"%");


        //其它百分比
        XWPFTableCell otherPerCell = percentageRow.getCell(22);
        insertValue(percentageRow,otherPerCell,size,typeface,(otherTotal.divide(total, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)))+"%");


        // 合并单元格，室内外财产百分比
        mergeCells(percentageRow, 23, 24);
        XWPFTableCell indoorOutPerCell = percentageRow.getCell(23);
        insertValue(percentageRow,indoorOutPerCell,size,typeface,(indoorOutTotal.divide(total, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)))+"%");

        //合计百分比
        XWPFTableCell totalPerCell = percentageRow.getCell(25);
        insertValue(percentageRow,totalPerCell,size,typeface,(total.divide(total, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)))+"%");
    }

    private void insertValue(XWPFTableRow row,XWPFTableCell cell, Integer size, String typeface,String value){
        if(cell == null){
            cell= row.addNewTableCell();
        }
        List<XWPFParagraph> lifeLineCellParagraphs = cell.getParagraphs();
        for (XWPFParagraph paragraph : lifeLineCellParagraphs) {
            XWPFRun run = paragraph.createRun();
            run.setText(value);
            run.setFontSize(size);
            run.setFontFamily(typeface);
            paragraph.setAlignment(ParagraphAlignment.CENTER);
        }
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
    }

    // 合并单元格的方法
    private static void mergeCells(XWPFTableRow row, int fromCell, int toCell) {
        for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
            if (cellIndex == fromCell) {
                XWPFTableCell cell = row.getCell(cellIndex);
                if(cell == null){
                    cell= row.addNewTableCell();
                }
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                XWPFTableCell cell = row.getCell(cellIndex);
                if(cell == null){
                    cell= row.addNewTableCell();
                }
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    // 计算合计值
    private static List<String> calculateTotal(List<List<String>> list) {
        List<String> totalRow = new ArrayList<>();
        totalRow.add("小计");

        // 遍历每一列
        for (int col = 1; col < list.get(0).size(); col++) {
            double sum = 0.0;

            // 遍历每一行，累加值
            for (List<String> row : list) {
                sum += Double.parseDouble(row.get(col));
            }
            // 将合计值添加到合计行
            totalRow.add(String.valueOf(sum));
        }
        return totalRow;
    }

    private void eachTable(List<XWPFTableRow> rows, Map reportData) {
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                //判断单元格内容是否可以替换
                String cellText = cell.getText();
                if (StrUtil.isNotBlank(cellText) && cellText.contains("{")) {
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (XWPFRun run : runs) {
                            run.setText(changeValue(run.toString(), reportData), 0);
                        }
                    }
                }
            }
        }
    }

    private String changeValue(String value, Map reportData) {
        Set<Map.Entry<String, String>> textSets = reportData.entrySet();
        for (Map.Entry<String, String> textSet : textSets) {
            //匹配模板与替换值 格式${key}
            String key = "{" + textSet.getKey() + "}";
            if (value.indexOf(key) != -1) {
                value = value.replace(key, textSet.getValue());
            }
        }
        return value;
    }

    private void replaceInPara(CustomXWPFDocument xwpfDocument, Map reportData) {
        Iterator<XWPFParagraph> iterator = xwpfDocument.getParagraphsIterator();
        XWPFParagraph para;
        //center是为了给标题加粗
        int center = 0;
        while (iterator.hasNext()) {
            para = iterator.next();
            para.setWordWrapped(true);
            //行间距
            //para.setSpacingBefore(100);
            center = this.replaceInPara(para, reportData, xwpfDocument, center);
        }
    }

    private int replaceInPara(XWPFParagraph para, Map<String, Object> params, CustomXWPFDocument doc, int center) {

        List<XWPFRun> runs;
        Matcher matcher;
        String paragraphText = para.getParagraphText();
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            int temp = 0;
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                int fontSize = run.getFontSize();
                fontSize = getFontSize(fontSize);
                String fontFamily = run.getFontFamily();
                String runText = run.toString().trim();
                if ("".equals(runText)) {
                    continue;
                }
                if (runText.contains("{") && !runText.contains("}") && runText.length() > 1) {
                    runText = runText + "}";
                }
                if ("{".equals(runText)) {
                    temp = 1;
                }

                if (temp == 1) {
                    if (!"{".equals(runText) && !"}".equals(runText)) {
                        runText = "{" + runText + "}";
                        temp = 0;
                    }
                }
                boolean contains = runText.contains("{");
                if (!runText.contains("{") && !runText.contains("}")) {
                    continue;
                }
                //获取{}中的值
                int firstIndex = runText.indexOf("{");
                int endIndex = runText.indexOf("}");
                int lastIndex = runText.lastIndexOf("}");
                if (firstIndex != -1 && firstIndex + 1 == endIndex) {
                    continue;
                }
                if (endIndex != lastIndex) {
                    //表示存在多个{}
                    //分别获取每一个{}中的值runText
                    List<String> keys = getEveryKey(runText);
                    if (PlatformObjectUtils.isNotEmpty(keys)) {
                        for (String key : keys) {
                            Object o = params.get(key);
                            if (PlatformObjectUtils.isEmpty(o)) {
                                runText = runText.replace("{" + key + "}", "");
                            } else {
                                runText = runText.replace("{" + key + "}", o.toString());
                            }
                        }
                        para.removeRun(i);
                        XWPFRun xwpfRun = para.insertNewRun(i);
                        xwpfRun.setFontSize(fontSize);
                        xwpfRun.setFontFamily("".equals(fontFamily) ? "Times New Roman" : fontFamily);
                        if (para.getParagraphText().contains("title")) {
                            xwpfRun.setFontSize(fontSize);
                            xwpfRun.setFontFamily("".equals(fontFamily) ? "Times New Roman" : fontFamily);
                            xwpfRun.setBold(true);
                        }
                        xwpfRun.setText(runText);
                        break;
                    }
                } else {
                    if (firstIndex > -1 || endIndex > -1) {
                        if (runText.startsWith("{image-")) {
                            runText = runText.replace("{", "").replace("}", "");
                            String[] split = runText.split("-");
                            if (split.length == 2 && StringUtils.isNotBlank(split[1]) && params.containsKey(split[1])) {
                                try {
                                    List<String> imgurls = (List<String>) params.get(split[1]);
                                    int a = 0;
                                    for (String imgurl : imgurls) {
                                        String picType = null;
                                        String[] split1 = imgurl.split(",");
                                        imgurl = split1[1];
                                        if (imgurl.contains(".")) {
                                            picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
                                        }
                                        InputStream inputStream = new FileInputStream(imgurl);
                                        int width = Units.toEMU(Double.parseDouble("280"));
                                        int height = Units.toEMU(Double.parseDouble("200"));
                                        run.setText("\t", a);
                                        a = a + 3;
                                        run.addPicture(inputStream, getPictureType(picType), "", width, height);
                                        run.setText("\r\n");
                                        run.setText(split1[0] + "\r\n");
                                        para.setAlignment(ParagraphAlignment.CENTER);
//                                        run.setText("\r\n");
                                        run.setBold(true);
                                    }
                                } catch (IOException | InvalidFormatException e) {

                                }
                            }
                        } else {
                            center++;
                            if ("{".equals(runText) || "}".equals(runText)) {
                                runText = "";
                            } else {
                                String key = runText.substring(firstIndex + 1, endIndex);
                                Object o = params.get(key);
                                if (PlatformObjectUtils.isEmpty(o) || "".equals(o)) {
                                    runText = runText.replace("{" + key + "}", "");
                                } else {
                                    runText = runText.replace("{" + key + "}", o.toString());
                                }
                            }
                            para.removeRun(i);
                            XWPFRun xwpfRun = para.insertNewRun(i);
                            xwpfRun.setFontSize(fontSize);
                            xwpfRun.setFontFamily(fontFamily);
                            if (center == 1 || center == 2) {
                                xwpfRun.setBold(true);
                            }
                            xwpfRun.setText(runText);
                        }
                        //break;
                    }
                }
            }
        }
        return center;
    }

    private int getFontSize(int fontSize) {
        if (fontSize == 26) return 26;
        if (fontSize == 22) return 22;
        if (fontSize == 20) return 20;
        if (fontSize == 16) return 16;
        return 14;
    }

    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    private static int getPictureType(String picType) {
        int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
        if (picType != null) {
            if (picType.equalsIgnoreCase("png")) {
                res = CustomXWPFDocument.PICTURE_TYPE_PNG;
            } else if (picType.equalsIgnoreCase("dib")) {
                res = CustomXWPFDocument.PICTURE_TYPE_DIB;
            } else if (picType.equalsIgnoreCase("emf")) {
                res = CustomXWPFDocument.PICTURE_TYPE_EMF;
            } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
                res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
            } else if (picType.equalsIgnoreCase("wmf")) {
                res = CustomXWPFDocument.PICTURE_TYPE_WMF;
            }
        }
        return res;
    }

    private List<String> getEveryKey(String runText) {
        List<Integer> list = new ArrayList<>();
        List<String> keyList = new ArrayList<>();
        char[] chars = runText.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '{') {
                list.add(++i);
            }
            if (chars[i] == '}') {
                list.add(i);
            }
        }
        StringBuilder key = new StringBuilder("");
        for (int i = 0; i < list.size(); i++) {
            key.append(runText.substring(list.get(i), list.get(++i)));
            keyList.add(key.toString());
            key = new StringBuilder("");
        }

        return keyList;
    }

    private String getRealFileName(String fileName) {
        String preFileName = fileName.substring(0, fileName.lastIndexOf("."));
        // .jpg  .pdf  .txt  .docs
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        // 拼文件名  真实的文件名称
        String realFileName = preFileName + "_" + System.currentTimeMillis() + fileType;
        return realFileName;
    }

    private AttachmentInfoEntity buildAttachment(String uuid, String fileName, String dateDir, String realFileName) {
        AttachmentInfoEntity attachmentInfoEntity = new AttachmentInfoEntity();
        attachmentInfoEntity.setAttachId(uuid);
        attachmentInfoEntity.setAttachName(fileName);
        attachmentInfoEntity.setAttachPath(dateDir + "/" + realFileName);
        attachmentInfoEntity.setFileDirId(localDir);
        attachmentInfoEntity.setIsValid("1");
        attachmentInfoEntity.setIsCompleted("1");
        return attachmentInfoEntity;
    }


    private Map getReportData1() throws ParseException {
        Map<String, Object> map = new HashMap<>();
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();//获取当前地震事件
        String xsemId = currentEvent.getXsemId();
        BigDecimal longitude = currentEvent.getLongitude();
        BigDecimal latitude = currentEvent.getLatitude();
        String eventTime = currentEvent.getEventTime();
        String eventCode = currentEvent.getEventCode();
        String magnitude = currentEvent.getMagnitude();
        //地震事件名称
        map.put("name", currentEvent.getEventName());
        //todo 暂定 单位
        map.put("unit", "单位--");
        //生成时间
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        map.put("time", dateFormat.format(new Date()));

        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat eventTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // 将字符串解析为Date对象
        Date eventTimeDate = originalFormat.parse(eventTime);
        //发震时间
        map.put("eventTime", eventTimeFormat.format(eventTimeDate));
        //震中位置
        map.put("epicentralSite", currentEvent.getEpicentralSite());
        //经纬度
        map.put("latAndLongitude", longitude+" "+latitude);
        //震级
        map.put("magnitude", currentEvent.getMagnitude());
        //灾区各县201灾区社会经济状况9年经济状况（亿元）
        List<List<String>> tableData2= new ArrayList<>();
        //地震灾区范围内的县
        List<HouseCategoryArea> HouseCategoryAreaList=houseCategoryAreaRepository.getALlCountyByXsemCode(xsemId);
        StringBuilder county=new StringBuilder("");
        if(HouseCategoryAreaList.size()>0){
            for(HouseCategoryArea item:HouseCategoryAreaList){
                county.append(item.getCounty()).append("、");
                List<String> list = new ArrayList<>();
                list.add(item.getCounty());
                tableData2.add(list);
            }
            map.put("affectedCounties",county.substring(0,county.length()-1));
        }
        //伤亡人数
        PersonnelInjuryAssessment personnelInjuryAssessment=enterpriseDirectEconomyRepository.getPeopleNumberByXsemId(xsemId);
        if(!PlatformObjectUtils.isEmpty(personnelInjuryAssessment)){
            //死亡人数
            map.put("deathPeople", personnelInjuryAssessment.getDeath());
            //失踪人数
            map.put("missing", personnelInjuryAssessment.getMissing());
            //重伤人数
            map.put("badlyInjured", personnelInjuryAssessment.getBadlyInjured());
            //轻伤人数
            map.put("minorInjured", personnelInjuryAssessment.getMinorInjury());
            //受伤人数
            map.put("injured", personnelInjuryAssessment.getBadlyInjured().add(personnelInjuryAssessment.getMinorInjury()));
        }
        //直接经济损失
        EconomicLossesSummary economicLossesSummary=enterpriseDirectEconomyRepository.getDirEcoLossesByXsemId(xsemId);
        if(!PlatformObjectUtils.isEmpty(economicLossesSummary)){
            //直接经济损失
            map.put("dirEcoLosses",economicLossesSummary.getTotal());
        }
        //todo 暂定 地震所属省局
        map.put("provincialBureaus", "地震所属省局--");

        //现场人员人数
        Integer totalPeople=personnelManagementRepository.countByXsemId(xsemId);
        map.put("totalPeople",totalPeople );
        //todo 暂定 直属单位
        map.put("unitsDirectlyUnder", "直属单位--");
        //todo 暂定 参与省局
        map.put("involvedProvincialBureau", "参与省局--");
        //发震时间（精确到日）
        DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime = inputFormat.parse(eventTime);
        String eventDate = outputFormat.format(dateTime);
        map.put("eventDate", eventDate);
        //结束时间（精确到日）
        DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        //map.put("endTime",dateFormat1.format(currentEvent.getEndTime()));

        //抽样点个数
        Integer samplingPoint=samPoiDataRepository.countByXsemId(xsemId);
        map.put("samplingPoint",samplingPoint );
        //生命线调查个数
        Integer lifelineNumber=lifelineRepository.countByXsemId(xsemId);
        map.put("lifelineNumber",lifelineNumber );
        //经度
        map.put("longitude", longitude+"");
        //纬度
        map.put("latitude", latitude+"");
        //震源深度
        map.put("sourceDepth", currentEvent.getSourceDepth()+"");


        //余震序列
        //3.0级及以上地震数量
        Integer earthquakeNum1 = aftershockSequenceRepository.getAftershockSequenceByCondition(eventTime,"3.0","");
        //8.0级及以上地震数量
        Integer earthquakeNum2 = aftershockSequenceRepository.getAftershockSequenceByCondition(eventTime,"8.0","");
        //7.0～7.9级地震数量
        Integer earthquakeNum3 = aftershockSequenceRepository.getAftershockSequenceByCondition(eventTime,"7.0","7.9");
        //6.0～6.9级地震数量
        Integer earthquakeNum4 = aftershockSequenceRepository.getAftershockSequenceByCondition(eventTime,"6.0","6.9");
        //5.0～5.9级地震数量
        Integer earthquakeNum5 = aftershockSequenceRepository.getAftershockSequenceByCondition(eventTime,"5.0","5.9");
        //4.0～4.9级地震数量
        Integer earthquakeNum6 = aftershockSequenceRepository.getAftershockSequenceByCondition(eventTime,"4.0","4.9");
        //3.0～3.9级地震数量
        Integer earthquakeNum7 = aftershockSequenceRepository.getAftershockSequenceByCondition(eventTime,"3.0","3.9");
        map.put("earthquakeNum1",earthquakeNum1.toString());
        map.put("earthquakeNum2",earthquakeNum2.toString());
        map.put("earthquakeNum3",earthquakeNum3.toString());
        map.put("earthquakeNum4",earthquakeNum4.toString());
        map.put("earthquakeNum5",earthquakeNum5.toString());
        map.put("earthquakeNum6",earthquakeNum6.toString());
        map.put("earthquakeNum7",earthquakeNum7.toString());



        List<InstrumentIntensity> intensityList=instrumentIntensityRepository.getTopFiveStation(xsemId);
        Map<String,List<List<String>>> tableData1 = new LinkedHashMap<>();
        if (intensityList.size()>0){
            List<String> stationNames = intensityList.stream()
                    .map(InstrumentIntensity::getStationName)
                    .collect(Collectors.toList());
            String stationNameStr = String.join("、", stationNames);
            //台站名称
            map.put("stationName", stationNameStr);


            //表1-2 震区各观测点获得的主震最大加速度
            Map<String, List<InstrumentIntensity>> intensityMap = new HashMap<>();
            intensityMap.put(magnitude, intensityList);
            intensityMap.forEach((k,v)->{
                List<List<String>> tempList = new ArrayList<>();
                for (InstrumentIntensity item : v) {
                    List<String> list = new ArrayList<>();
                    list.add(magnitude);
                    list.add(item.getStationName());
                    list.add(item.getEpicenterDistance().toString());
                    list.add(item.getPgaEw().toString());
                    list.add(item.getPgaNs().toString());
                    list.add(item.getPgaUd().toString());

                    tempList.add(list);
                }
                tableData1.put(k,tempList);
            });
            map.put("tableData1",tableData1);
        }




        //灾区社会经济状况
        map.put("tableData2",tableData2);
        //发震前一年


        // 将输入字符串解析为LocalDateTime对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime inputDateTime = LocalDateTime.parse(eventTime, formatter);

        // 获取上一年的日期
        LocalDateTime previousYearDateTime = inputDateTime.minusYears(1);

        // 将结果转换为字符串
        String eventTimePreviousYear = previousYearDateTime.format(formatter);
        map.put("eventTimePreviousYear", eventTimePreviousYear);

        //结构类型(筛选出总面积不为0的结构类型)，统计类型总数
        HouseCategoryArea houseCategoryArea= houseCategoryAreaRepository.getTypeTotalAreaByXsemCode(xsemId);
        StringBuilder structureType=new StringBuilder("");
        int count=0;
        if (!(houseCategoryArea.getV1Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("I类、");
            count++;
        }
        if (!(houseCategoryArea.getV2Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("II类、");
            count++;
        }
        if (!(houseCategoryArea.getV3Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("III-1类、");
            count++;
        }
        if (!(houseCategoryArea.getV4Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("III-2类、");
            count++;
        }
        if (!(houseCategoryArea.getV5Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("Ⅳ类、");
            count++;
        }
        if (!(houseCategoryArea.getV6Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("V-1类、");
            count++;
        }
        if (!(houseCategoryArea.getV7Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("V-2类、");
            count++;
        }
        if (!(houseCategoryArea.getV8Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("V-3类、");
            count++;
        }
        if (!(houseCategoryArea.getV9Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("Ⅵ类、");
            count++;
        }
        if (!(houseCategoryArea.getV10Area().compareTo(BigDecimal.ZERO) == 0)) {
            structureType.append("Ⅶ类、");
            count++;
        }
        if(structureType.length()!=0){
            map.put("structureType",structureType.substring(0,structureType.length()-1));
            map.put("structureCount",count);
        }
        //6度及以上灾区范围的县
        List<String> countyList=shpDataService.getCountyByIntensityAndXsemId("6",xsemId);
        map.put("allCounty",String.join("、", countyList));
        map.put("countyNumber",countyList.size());

        //灾区基础资料
        List<HouseCategoryAreaVo> houseCategoryAreaList = houseCategoryAreaRepository.getALlSubzoneCountyByXsemCode(xsemId);
        Map<String,List<List<String>>> tableData3 = new LinkedHashMap<>();
        if(houseCategoryAreaList.size()>0){
            Map<String, List<HouseCategoryAreaVo>> houseCategoryAreaMap = houseCategoryAreaList.stream().
                    collect(Collectors.groupingBy(HouseCategoryAreaVo::getEvaluationSubareaName));

            houseCategoryAreaMap.forEach((k,v)->{
                List<List<String>> tempList = new ArrayList<>();
                for (HouseCategoryAreaVo houseCategoryAreaVo : v) {
                    List<String> list = new ArrayList<>(2);
                    list.add(houseCategoryAreaVo.getEvaluationSubareaName());
                    list.add(houseCategoryAreaVo.getCounty());
                    tempList.add(list);
                }
                List<String> list = new ArrayList<>(2);
                list.add(k);
                list.add("小计");
                tempList.add(list);
                tableData3.put(k,tempList);
            });
            List<List<String>> tempList = new ArrayList<>();
            List<String> list = new ArrayList<>(2);
            list.add("合计");
            list.add("-");
            tempList.add(list);
            tableData3.put("合计",tempList);
        }
        map.put("tableData3",tableData3);

        //烈度图解说
        String remark=shpDataService.getRemark(xsemId);
        map.put("remark",remark);
        //失去住所人数
        ResettlementPopulationEvaluation resettlePeople=enterpriseDirectEconomyRepository.getResettlePeopleByXsemId(xsemId);
        if(!PlatformObjectUtils.isEmpty(resettlePeople)){
            map.put("resettlePeople",resettlePeople.getResettlePeopleNumber());
        }
        //评估区的划分
        //评估子区数量（按烈度区分子区
        List<SurTaskManage> subzoneList = surTaskManageRepository.getTaskByTypeAndXsemId(xsemId);
       if(subzoneList.size()>1){


           StringBuilder intensityCoverageArea=new StringBuilder("");
           StringBuilder intensityCity6=new StringBuilder("");
           StringBuilder intensityRural6=new StringBuilder("");
           StringBuilder intensityCity7=new StringBuilder("");
           StringBuilder intensityRural7=new StringBuilder("");
           StringBuilder intensityCity8=new StringBuilder("");
           StringBuilder intensityRural8=new StringBuilder("");
           StringBuilder intensityCity9=new StringBuilder("");
           StringBuilder intensityRural9=new StringBuilder("");
           StringBuilder intensityCity10=new StringBuilder("");
           StringBuilder intensityRural10=new StringBuilder("");

           for(SurTaskManage item:subzoneList){
               DrawSeismicInfluence drawSeismicInfluence=shpDataService.findBySiId(item.getSiId());
               if(PlatformObjectUtils.isNotEmpty(drawSeismicInfluence)){
                   String intensity = drawSeismicInfluence.getIntensity();
                   if(XczhConstants.INTENSITY_SIX.equals(intensity)){
                       if("城市评估区".equals(item.getEvaluationSubareaType())){
                           intensityCity6.append(item.getEvaluationSubareaName()).append("、");
                       }else{
                           intensityRural6.append(item.getEvaluationSubareaName()).append("、");
                       }
                   }else if(XczhConstants.INTENSITY_SEVEN.equals(intensity)){
                       if("城市评估区".equals(item.getEvaluationSubareaType())){
                           intensityCity7.append(item.getEvaluationSubareaName()).append("、");
                       }else{
                           intensityRural7.append(item.getEvaluationSubareaName()).append("、");
                       }
                   }else if(XczhConstants.INTENSITY_EIGHT.equals(intensity)){
                       if("城市评估区".equals(item.getEvaluationSubareaType())){
                           intensityCity8.append(item.getEvaluationSubareaName()).append("、");
                       }else{
                           intensityRural8.append(item.getEvaluationSubareaName()).append("、");
                       }
                   }else if(XczhConstants.INTENSITY_NINE.equals(intensity)){
                       if("城市评估区".equals(item.getEvaluationSubareaType())){
                           intensityCity9.append(item.getEvaluationSubareaName()).append("、");
                       }else{
                           intensityRural9.append(item.getEvaluationSubareaName()).append("、");
                       }
                   }else if(XczhConstants.INTENSITY_TEN.equals(intensity)){
                       if("城市评估区".equals(item.getEvaluationSubareaType())){
                           intensityCity10.append(item.getEvaluationSubareaName()).append("、");
                       }else{
                           intensityRural10.append(item.getEvaluationSubareaName()).append("、");
                       }
                   }
               }
           }
           if(!(intensityCity6.length()==0)){
               intensityCoverageArea.append("6度区分为城市评估区").append(intensityCity6.substring(0,intensityCity6.length()-1));
               if(!(intensityRural6.length()==0)){
                   intensityCoverageArea.append("和农村评估区").append(intensityRural6.substring(0,intensityRural6.length()-1));
               }
               intensityCoverageArea.append("，");
           }
           if(!(intensityCity7.length()==0)){
               intensityCoverageArea.append("7度区分为城市评估区").append(intensityCity7.substring(0,intensityCity7.length()-1));
               if(!(intensityRural7.length()==0)){
                   intensityCoverageArea.append("和农村评估区").append(intensityRural7.substring(0,intensityRural7.length()-1));
               }
               intensityCoverageArea.append("，");
           }
           if(!(intensityCity8.length()==0)){
               intensityCoverageArea.append("8度区分为城市评估区").append(intensityCity8.substring(0,intensityCity8.length()-1));
               if(!(intensityRural8.length()==0)){
                   intensityCoverageArea.append("和农村评估区").append(intensityRural8.substring(0,intensityRural8.length()-1));
               }
               intensityCoverageArea.append("，");
           }
           if(!(intensityCity9.length()==0)){
               intensityCoverageArea.append("9度区分为城市评估区").append(intensityCity9.substring(0,intensityCity9.length()-1));
               if(!(intensityRural9.length()==0)){
                   intensityCoverageArea.append("和农村评估区").append(intensityRural9.substring(0,intensityRural9.length()-1));
               }
               intensityCoverageArea.append("，");
           }
           if(!(intensityCity10.length()==0)){
               intensityCoverageArea.append("10度区分为城市评估区").append(intensityCity10.substring(0,intensityCity10.length()-1));
               if(!(intensityRural10.length()==0)){
                   intensityCoverageArea.append("和农村评估区").append(intensityRural10.substring(0,intensityRural10.length()-1));
               }
               intensityCoverageArea.append("，");
           }
           map.put("intensityCoverageArea",intensityCoverageArea.substring(0,intensityCoverageArea.length()-1));
       }

        map.put("subzoneNumber",subzoneList.size());

        //房屋破坏比汇总表（%）
        List<HouseFailureRatioEntity> failureRatioList=houseEconomicLossAssessRepository.getHouseFailureRatioByXsemId(xsemId);
        Map<String,List<List<String>>> tableData4 = new LinkedHashMap<>();
        if(failureRatioList.size()>0){
            Map<String, List<HouseFailureRatioEntity>> failureRatioMap = failureRatioList.stream().collect(
                    Collectors.groupingBy(HouseFailureRatioEntity::getEvaluationSubareaName));
            failureRatioMap.forEach((k,v)->{
                List<List<String>> tempList = new ArrayList<>();
                for (HouseFailureRatioEntity item : v) {
                    List<String> list = new ArrayList<>();
                    list.add(item.getEvaluationSubareaName());
                    String structureTypeName = dictService.getValueByDictCodeAndKey("jglx",item.getStructureType());
                    list.add(structureTypeName);
                    list.add(item.getIntactRatio());
                    list.add(item.getMinorRatio());
                    list.add(item.getModerateRatio());
                    list.add(item.getSeriousRatio());
                    list.add(item.getDestroyRatio());
                    tempList.add(list);
                }
                tableData4.put(k,tempList);
            });
        }
        map.put("tableData4",tableData4);
        //房屋损失比
        HouseLossRatioEntity houseLossRatio = houseEconomicLossAssessRepository.getHouseLossRatio(xsemId);
        if(!PlatformObjectUtils.isEmpty(houseLossRatio)){
            map.put("intact1",houseLossRatio.getIntact1());
            map.put("minor1",houseLossRatio.getMinor1());
            map.put("moderate1",houseLossRatio.getModerate1());
            map.put("serious1",houseLossRatio.getSerious1());
            map.put("destory1",houseLossRatio.getDestroy1());

            map.put("intact2",houseLossRatio.getIntact2());
            map.put("minor2",houseLossRatio.getMinor2());
            map.put("moderate2",houseLossRatio.getModerate2());
            map.put("serious2",houseLossRatio.getSerious2());
            map.put("destory2",houseLossRatio.getDestroy2());

            map.put("intact3",houseLossRatio.getIntact3());
            map.put("minor3",houseLossRatio.getMinor3());
            map.put("moderate3",houseLossRatio.getModerate3());
            map.put("serious3",houseLossRatio.getSerious3());
            map.put("destory3",houseLossRatio.getDestroy3());

            map.put("intact4",houseLossRatio.getIntact4());
            map.put("minor4",houseLossRatio.getMinor4());
            map.put("moderate4",houseLossRatio.getModerate4());
            map.put("serious4",houseLossRatio.getSerious4());
            map.put("destory4",houseLossRatio.getDestroy4());
        }
        //重置单价（元/平方米）
        List<ResetPrice> resetPriceList = resetPriceRepository.getResetPriceByXsemId(xsemId);
        List<List<String>> tableData6= new ArrayList<>();
        int serialNumber=0;
        for(ResetPrice item:resetPriceList){
            List<String> list = new ArrayList<>();
            list.add(serialNumber+"");
            String structureTypeName = dictService.getValueByDictCodeAndKey("jglx",item.getStructureType());
            list.add(structureTypeName);
            list.add(item.getResetPrice());
            tableData6.add(list);
            serialNumber++;
        }
        map.put("tableData6",tableData6);
        //todo 暂定 房屋破坏面积
        //todo 总建筑面积(目前未合并，后面需要合并)
        List<HouseCategoryArea> totalAreaList = houseCategoryAreaRepository.getTotalAreaListByXsemCode(xsemId);
        List<List<String>> tableData9= new ArrayList<>();
        if(houseCategoryAreaList.size()>0){
            for(HouseCategoryArea item:totalAreaList){
                List<String> list = new ArrayList<>();
                list.add(item.getEvaluationSubareaName());
                list.add(item.getProvince());
                list.add(item.getCity());
                list.add(item.getCounty());
                list.add(item.getHousePurposeName());
                list.add(item.getV1Area()+"");
                list.add(item.getV2Area()+"");
                list.add(item.getV3Area()+"");
                list.add(item.getV4Area()+"");
                list.add(item.getV5Area()+"");
                list.add(item.getV6Area()+"");
                list.add(item.getV7Area()+"");
                list.add(item.getV8Area()+"");
                list.add(item.getV9Area()+"");
                list.add(item.getV10Area()+"");
                tableData9.add(list);
            }
        }
        map.put("tableData9",tableData9);
        //报表类型
        List<LifelineSystemLoss> reportList=enterpriseDirectEconomyRepository.getReportLossByXsemId(xsemId);
        if(reportList.size()>0){
            StringBuilder reportType=new StringBuilder();
            for(LifelineSystemLoss item:reportList){
                if(!(item.getLoss().compareTo(BigDecimal.ZERO) == 0)){
                    String typeName = dictService.getValueByDictCodeAndKey("bblb",item.getLifelineType());
                    reportType.append(typeName).append("、");
                }
            }
            if(PlatformObjectUtils.isNotEmpty(reportType.toString())){
                map.put("reportType", reportType.substring(0,reportType.length()-1));
            }else{
                map.put("reportType", reportType);
            }
        }

        //房屋直接经济损失
        List<AdministrationAreaHousesDirectEconomicLosses> administrationData = houseEconomicLossAssessRepository.getLossesByXsemId(xsemId);
        if(administrationData.size()>0){
            BigDecimal directEconomicLoss=BigDecimal.ZERO;
            StringBuilder countyLoss=new StringBuilder("");
            for(AdministrationAreaHousesDirectEconomicLosses item:administrationData){
                directEconomicLoss=directEconomicLoss.add(item.getTotalLoss().divide(new BigDecimal(10000)).
                        setScale(2, BigDecimal.ROUND_HALF_UP));
                countyLoss.append(item.getCounty()).append(item.getTotalLoss().divide(new BigDecimal(10000)).
                        setScale(2, BigDecimal.ROUND_HALF_UP)).append("万元").append("，");
            }
            map.put("directEconomicLoss",directEconomicLoss);
            map.put("countyLoss",countyLoss.toString());
        }

        //todo 地震直接经济损失 (目前未合并，后面需要合并)
        List<EconomicLossesSummary> economicLossesSummaryList = enterpriseDirectEconomyRepository.getEconomicLossesSummaryData(xsemId);
        List<List<String>> tableData10= new ArrayList<>();
        if(houseCategoryAreaList.size()>0){
            for(EconomicLossesSummary item:economicLossesSummaryList){
                    List<String> list = new ArrayList<>();
                    list.add(item.getProvince()+item.getCity()+item.getCounty());
                    list.add(item.getRuralResidential()+"");
                    list.add(item.getRuralPublic()+"");
                    list.add(item.getUrbanResidential()+"");
                    list.add(item.getUrbanPublic()+"");
                    list.add(item.getGovernmentOffice()+"");
                    list.add(item.getEducationSystem()+"");
                    list.add(item.getHealthcareSystem()+"");
                    list.add(item.getOtherUsage()+"");
                    list.add(item.getElectricity()+"");
                    list.add(item.getWaterSupplyAndDrainage()+"");
                    list.add(item.getGasSupply()+"");
                    list.add(item.getHeatingSupply()+"");
                    list.add(item.getTraffic()+"");
                    list.add(item.getOilAndGasPipelines()+"");
                    list.add(item.getCommunication()+"");
                    list.add(item.getBroadcastingAndTelevision()+"");
                    list.add(item.getMunicipalFacilities()+"");
                    list.add(item.getRailway()+"");
                    list.add(item.getEnterprise()+"");
                    list.add(item.getWaterConservancy()+"");
                    list.add(item.getCulturalHeritage()+"");
                    list.add(item.getOther()+"");
                    list.add(item.getIndoorProperty()+"");
                    list.add(item.getOutdoorProperty()+"");
                    list.add(item.getTotal()+"");
                    tableData10.add(list);
            }
        }
        map.put("tableData10",tableData10);
        return map;
    }
}
